﻿var _global_vars = ["WebPath","ImagePath","CssPath","JsPath"];
var _global_functions = ["BuildUrl()"];

function BuildResult()
{
	var result = {Widget:_widget};

	if (_widget.Record != null)
	{
		var record = "";
		var col = "";
		var row = "";
		var list = "";

		//生成客户端代码（ClientCode）
		var recordCount = Math.min(_widget.Data.length, _widget.List.PageSize);
		var i = 0;
		for (; i < recordCount; i++)
		{
			record = "";
			if (col.length == 0)
				record += _widget.RecordSeparator;
			record += _widget.Record.Text;
			for (var j = 0; j < _widget.Record.Vars.length; j++)
			{
				var re = new RegExp("\{#" + _widget.Record.Vars[j].Name.replace("(", "\\(").replace(")", "\\)") + "#\}", "g");
				record = record.replace(re, _widget.Data[i][j]);
			}
			
			if (col.length == 0)
				col += _widget.Col.Text;
			col = col.replace("{#_Record#}", record + "{#_Record#}");
			
			if (_widget.Col.MaxRecord != 0 && (i + 1) % _widget.Col.MaxRecord == 0)
			{
				col = col.replace("{#_Record#}", "");
				if (row.length == 0)
				{
					row += _widget.Row.Text;
					row = row.replace("{#_Col#}", col + "{#_Col#}");
				}
				else
				{
					row = row.replace("{#_Col#}", _widget.ColSeparator + col + "{#_Col#}");
				}
				col = "";
				
				if (_widget.Row.MaxCol != 0 && ((i + 1) / _widget.Col.MaxRecord) % _widget.Row.MaxCol == 0)
				{
					row = row.replace("{#_Col#}", "");
					if (list.length == 0)
					{
						list += _widget.List.Text;
						list = list.replace("{#_Row#}", row + "{#_Row#}");
					}
					else
					{
						list = list.replace("{#_Row#}", _widget.RowSeparator + row + "{#_Row#}");
					}
					row = "";
				}
			}
		}
		
		if (col.length > 0)
		{
			col = col.replace("{#_Record#}", "");
			if (row.length == 0)
				row += _widget.Row.Text;
			if (_widget.Col.MaxRecord != 0 && i / _widget.Col.MaxRecord > 1)
				row = row.replace("{#_Col#}", _widget.ColSeparator + col);
			else
				row = row.replace("{#_Col#}", col);
		}
		
		if (row.length > 0)
		{
			row = row.replace("{#_Col#}", "");
			if (list.length == 0)
				list += _widget.List.Text;
			if (_widget.Col.MaxRecord != 0 && _widget.Row.MaxCol != 0 && (i / _widget.Col.MaxRecord) / _widget.Row.MaxCol > 1)
				list = list.replace("{#_Row#}", _widget.RowSeparator + row);
			else
				list = list.replace("{#_Row#}", row);
		}
		
		list = list.replace("{#_Row#}", "");
		result.Html = _widget.Html.Text.replace("{#_List#}", list);
		
		//生成服务器端代码（ServerCode）
		if (_widget.List.Object.length > 0)
		{
			var sep;

			record = "<ali:Record>" + $.trim(_widget.Record.Text);
			for (var i = 0; i < _widget.Record.Vars.length; i++)
			{
				record = record.replace(new RegExp("\\{#" + _widget.Record.Vars[i].Name.replace("(", "\\(").replace(")", "\\)") + "#\\}", "g"), "<%=" + _widget.Record.Vars[i].Value + "%>");
			}
			sep = $.trim(_widget.RecordSeparator);
			if (sep.length > 0)
				record += "<ali:Separator>" + sep + "</ali:Separator>";
			record += "</ali:Record>";
			
			if (_widget.Col.IsExist)
			{
				col = "<ali:Col" + (_widget.Col.MaxRecord == 0 ? "" : " MaxRecord=\"" + _widget.Col.MaxRecord + "\"") + ">" + $.trim(_widget.Col.Text);
				for (var i = 0; i < _widget.Col.Vars.length; i++)
				{
					col = col.replace(new RegExp("\\{#" + _widget.Col.Vars[i].Name + "#\\}", "g"), "<%=" + _widget.Col.Vars[i].Value + "%>");
				}
				sep = $.trim(_widget.ColSeparator);
				if (sep.length > 0)
					col += "<ali:Separator>" + sep + "</ali:Separator>";
				col += "</ali:Col>";
				col = col.replace("{#_Record#}", record);
			}
			else
			{
				col = record;
			}
			
			if (_widget.Row.IsExist)
			{
				row = "<ali:Row" + (_widget.Row.MaxCol == 0 ? "" : " MaxCol=\"" + _widget.Row.MaxCol + "\"") + ">" + $.trim(_widget.Row.Text);
				for (var i = 0; i < _widget.Row.Vars.length; i++)
				{
					row = row.replace(new RegExp("\\{#" + _widget.Row.Vars[i].Name + "#\\}", "g"), "<%=" + _widget.Row.Vars[i].Value + "%>");
				}
				sep = $.trim(_widget.RowSeparator);
				if (sep.length > 0)
					row += "<ali:Separator>" + sep + "</ali:Separator>";
				row += "</ali:Row>";
				row = row.replace("{#_Col#}", col);
			}
			else
			{
				row = col;
			}
				
			list = "<ali:List";
			if (_widget.List.Mark.length > 0)
				list += " Mark=\"" + _widget.List.Mark + "\"";
			list += " Object=\"" + _widget.List.Object + "\" Page=\"1\" PageSize=\"" + _widget.List.PageSize + "\""
			if (_widget.List.Condition.length > 0)
				list += " Condition=\"" + _widget.List.Condition + "\"";
			if (_widget.List.Sort.length > 0)
				list += " Sort=\"" + _widget.List.Sort + "\"";
			list += ">";
			list += $.trim(_widget.List.Text);
			for (var i = 0; i < _widget.List.Vars.length; i++)
			{
				list = list.replace(new RegExp("\\{#" + _widget.List.Vars[i].Name + "#\\}", "g"), "<%=" + _widget.List.Vars[i].Value + "%>");
			}
			list = list.replace("{#_Row#}", row);
			list += "</ali:List>";
			
			result.ServerCode = $.trim(_widget.Html.Text.replace("{#_List#}", list));
		}
	}
	else
	{
		//TODO：实现非列表的情况
	}
	
	result.Style = _widget.Style.replace("{Widget}", "." + _widget.ID);
	result.Insert = $("[name=Insert]").val();
	result.Json = JSON.stringify(_widget);
	return result;
}

function FromXmlNode(node)
{
	var widget = {ID:node.attr("ID"),Name:node.attr("Name"),Width:node.attr("Width")};
	
	//style
	var styleNode = node.find("Style");
	widget.Style = styleNode.length == 0 ? "" : styleNode.text();
	widget.Style = widget.Style.replace(/{Widget}/g, "." + widget.ID);
	widget.Style = widget.Style.replace(/..\/image\//g, _skin + "image/");
	
	//分析Record
	var record = node.children("Record");
	if (record.length > 0)
	{
		widget.Record = {};
		widget.Record.Text = record.text();
		widget.Record.Vars = [];
		
		var re = /\{#.*?#\}/g;
		var v;
		while ((v = re.exec(widget.Record.Text)) != null)
		{
			var newVar = {Name:v[0].substr(2, v[0].length - 4), Value:""};
			widget.Record.Vars.push(newVar);
		}
	}
				
	//分析Html
	widget.Html = {};
	widget.Html.Vars = [];
	var html = node.children("Html");
	if (html.length > 0)
	{
		widget.Html.Text = html.text();
		
		var re = /\{#.*?#\}/g;
		var v;
		while ((v = re.exec(widget.Html.Text)) != null)
		{
			var newVar = {Name:v[0].substr(2, v[0].length - 4), Value:""};
			if (newVar.Name == "_List")
				continue;

			widget.Html.Vars.push(newVar);
		}
	}
	else if (widget.Record != null)
	{
		widget.Html.Text = "{#_List#}";
	}
	
	widget.ByHand = true;
	if (widget.Record != null)
	{
		//分析List
		widget.List = {};
		widget.List.Vars = [];
		var list = node.children("List");
		if (list.length > 0)
		{
			widget.List.Text = list.text();
			
			//PageSize
			var pageSize = list.attr("PageSize");
			if (pageSize == null)
				widget.List.PageSize = 10;
			else
				widget.List.PageSize = parseInt(pageSize);
			
			var re = /\{#.*?#\}/g;
			var v;
			while ((v = re.exec(widget.List.Text)) != null)
			{
				var newVar = {Name:v[0].substr(2, v[0].length - 4), Value:""};
				if (newVar.Name == "_Row")
					continue;

				widget.List.Vars.push(newVar);
			}
		}
		else
		{
			widget.List.Text = "{#_Row#}";
			widget.List.PageSize = 10;
		}
		widget.List.Mark = "";
		widget.List.Object = "";
		widget.List.Condition = "";
		widget.List.Sort = "";

		//分析Row
		widget.Row = {};
		widget.Row.Vars = [];
		var row = node.children("Row");
		if (row.length > 0)
		{
			widget.Row.IsExist = true;
			widget.Row.Text = row.text();
			widget.Row.MaxCol = parseInt(node.attr("MaxCol"));
			
			var re = /\{#.*?#\}/g;
			var v;
			while ((v = re.exec(widget.Row.Text)) != null)
			{
				var newVar = {Name:v[0].substr(2, v[0].length - 4), Value:""};
				if (newVar.Name == "_Col")
					continue;

				widget.Row.Vars.push(newVar);
			}
		}
		else
		{
			widget.Row.IsExist = false;
			widget.Row.Text = "{#_Col#}";
			widget.Row.MaxCol = 0;
		}

		//分析Col
		widget.Col = {};
		widget.Col.Vars = [];
		var col = node.children("Col");
		if (col.length > 0)
		{
			widget.Col.IsExist = true;
			widget.Col.Text = col.text();
			widget.Col.MaxRecord = parseInt(node.attr("MaxRecord"));
			
			var re = /\{#.*?#\}/g;
			var v;
			while ((v = re.exec(widget.Col.Text)) != null)
			{
				var newVar = {Name:v[0].substr(2, v[0].length - 4), Value:""};
				if (newVar.Name == "_Record")
					continue;

				widget.Col.Vars.push(newVar);
			}
		}
		else
		{
			widget.Col.IsExist = false;
			widget.Col.Text = "{#_Record#}";
			widget.Col.MaxRecord = 0;
		}

		//分析RecordSeparator
		var rsNode = node.children("RecordSeparator");
		if (rsNode.length > 0)
			widget.RecordSeparator = rsNode.text();
		else
			widget.RecordSeparator = "";

		//分析ColSeparator
		var csNode = node.children("ColSeparator");
		if (csNode.length > 0)
			widget.ColSeparator = csNode.text();
		else
			widget.ColSeparator = "";

		//分析RowSeparator
		var rwsNode = node.children("RowSeparator");
		if (rwsNode.length > 0)
			widget.RowSeparator = rwsNode.text();
		else
			widget.RowSeparator = "";
	}
	
	return widget;
}

function PrepareWidget()
{
	var node = _config.find("Widget[ID=" + $("[name=Widget]").val() + "]");

	//分析Widget
	_widget = FromXmlNode(node);
	
	//设置皮肤
	_widget.Skin = $("[name=Skin]").val();
	_widget.SkinName = $("[name=Skin]").text();
}

function PrepareData()
{
	if (_widget.Record == null)
		return;

	if (_widget.Data.length < _widget.List.PageSize)
	{
		var data = "0000000000";
		_widget.Data = [];
		for (var i = 0; i < _widget.List.PageSize; i++)
		{
			var values = [];
			_widget.Data.push(values);
			for (var j = 0; j < _widget.Record.Vars.length; j++)
			{
				values.push(data);
			}
			data = data.replace(/\d/g, i + 1);
		}
	}
}

function Preview()
{
	var result = BuildResult();
	var html = "<style>" + result.Style + "</style><widget class='" + result.Widget.ID + "'>" + result.Html + "</widget>";
	$("#PreviewCode").html(HtmlEncode(html));
	$("#PreviewResult iframe").bind("load", function(){$("#PreviewResult iframe").contents().find("body").css("width", _widget.Width).html(html);}).attr("src", "preview.html");
}

function LoadConfig()
{
	SetStatusMessage(_lang_working);
	
	var js = document.getElementsByTagName("script");
	var template = js[js.length-1].src.substring(0,js[js.length-1].src.lastIndexOf("/")+1).replace("/js/", "/");
	
	$.ajax(
	{
		url : template + "vedit.xml",
		type : "GET",
		error : function(request)
		{
			$("[name=Skin]").change();
			$("[name=Instance]").change();
			SetStatusMessage();
		},
		success : function(data)
		{
			_config = $(data);
			$("[name=Skin]").change();
			$("[name=Instance]").change();
			SetStatusMessage();
		}
	});
}

function BuildList()
{
	if ($("[name=Object]").val() == "")
	{
		Alert(_lang_object_empty);
		return;
	}

	$("#VarTable tbody :text").each(function()
	{
		if (this.value == "")
		{
			Alert(_lang_var_empty, function(){this.select();}, this);
			return;
		}
	});

	var buildButton = $(this);
	buildButton[0].disabled = true;
	SetStatusMessage(_lang_working);

	$.ajax(
	{
		url : "ajax_list.aspx?InstanceInnerID=" + $("[name=Instance] :selected").data("innerid") + "&ObjectID=" + $("[name=Object]").val() + "&Condition=" + $("[name=Condition]").val() + "&Sort=" + $("[name=Sort]").val() + "&PageSize=" + _widget.List.PageSize,
		type : "GET",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			buildButton[0].disabled = false;
			SetStatusMessage();
		},
		success : function(data)
		{
			_widget.List.Mark = $("[name=Instance] :selected").data("Mark");
			_widget.List.Object = $("[name=Object] :selected").data("Name");
			_widget.List.Condition = $("[name=Condition]").val();
			_widget.List.Sort = $("[name=Sort]").val();
			
			$("#VarTable tbody :text").each(function(index, element)
			{
				_widget.Record.Vars[index].Value = element.value;
			});

			_widget.Data.length = 0;
			var records = eval(data);
			for (var i = 0; i < records.length; i++)
			{
				var values = [];
				_widget.Data.push(values);
				
				for (var j = 0; j < _widget.Record.Vars.length; j++)
				{
					var value = _widget.Record.Vars[j].Value;
					for (var k in records[i])
					{
						if (k = value)
						{
							value = unescape(records[i][k]);
							break;
						}
					}
					values.push(value);
				}
			}

			Preview();
			Alert(_lang_operation_success, function(){$("h1 a:first").click();}, this);
			
			buildButton[0].disabled = false;
			SetStatusMessage();
			
		}
	});
}

function Skin_OnChange()
{
	SetStatusMessage(_lang_get_widget);
	
	var template = $(this).val().replace(/\/\w+\/\w{3}\/$/, "/");

	$.ajax(
	{
		url : template + "vedit.xml",
		type : "GET",
		error : function(request)
		{
			if (request.status == 404)
				Alert(_lang_config_file_not_exist);
			else
				Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
			if (_config == null)
				_config = $(data);
			else
				_config.find("configuration").append($(data).find("configuration").children());

			var widget = $("[name=Widget]");
			widget[0].length = 0;
			_config.find("Widgets Widget[ID!=]").each(function()
			{
				var sel = "";
				if (_id != "" && _widget.ID == $(this).attr("ID"))
					sel = " selected='selected'";
				widget.append("<option value='" + $(this).attr("ID") + "'" + sel + ">" + $(this).attr("Name") + "</option>");
			});
			
			widget.change();

			SetStatusMessage();
		}
	});
}

function Widget_OnChange()
{
	if (_id == "")
	{
		//准备Widget
		PrepareWidget();
	
		//设置PageSize
		if (_widget.List != null)
			$("[name=PageSize]").val(_widget.List.PageSize);
		else
			$("[name=PageSize]").val(1);
	
		//准备测试数据
		PrepareData();
	}
	
	//生成并显示预览
	Preview()
	
	//变量重新生成
	var varTable = $("#VarTable tbody");
	varTable.empty();
	if (_widget.Record != null)
	{
		for (var i = 0; i < _widget.Record.Vars.length; i++)
		{
			varTable.append("<tr><th>" + _widget.Record.Vars[i].Name + "</th><td><input type='text' class='Width2'><select class='Width1'><option value=''>" + _lang_select + "</option></select><td></tr>");
		}
	}
}

function PageSize_OnChange()
{
	//设置PageSize
	if (_widget.List != null)
		_widget.List.PageSize = parseInt($("[name=PageSize]").val());
	
	//准备测试数据
	PrepareData();
	
	//生成并显示预览
	Preview();
}

function TabMenu_OnClick()
{
	var me = $(this);
	if (!me.hasClass("Selected"))
	{
		me.siblings().removeClass("Selected");
		me.addClass("Selected");
		
		var index = me.parent().children().index(this);
		
		//二级菜单
		var h2s = me.parent().parent().children("h2");
		h2s.hide();
		var h2 = h2s.eq(index);
		if (_debug)
			h2.show();
		
		//内容
		var divs = me.parent().parent().children("div");
		divs.hide();
		var id = h2.find(":checked").attr("id");
		if (id == "Result")
			$("#PreviewResult").show();
		else if (id == "Code")
			$("#PreviewCode").show();
		else if (id == "Auto")
			$("#PreviewAuto").show();
		else if (id == "Hand")
			$("#PreviewHand").show();
	}
	
	return false;
}

function SubMenu_OnClick()
{
	$(".Preview").hide();
	if (this.id == "Result")
		$("#PreviewResult").show();
	else if (this.id == "Code")
		$("#PreviewCode").show();
	else if (this.id == "Auto")
		$("#PreviewAuto").show();
	else if (this.id == "Hand")
		$("#PreviewHand").show();
}

function Instance_OnChange()
{
	if ($("[name=Instance] option").length == 1)
	{
		$.ajax(
		{
			url : "ajax_instances.aspx",
			type : "GET",
			success : function(data)
			{
				var allInstance = eval(data);
				for (var i = 0; i < allInstance.length; i++)
				{
					allInstance[i].ID = "{" + allInstance[i].ID.toUpperCase() + "}";
					allInstance[i].Mark = allInstance[i].ID;
				}

				_roldID = "{" + _roldID.toUpperCase() + "}";
				
				var right;
				_config.find("Rights > Right").each(function()
				{
					var me = $(this);
					if (typeof(me.attr("RoleID")) != "undefined" && me.attr("RoleID") != _roleID)
						return true;
					
					if (typeof(me.attr("Template")) != "undefined" && _skin.indexOf(me.attr("Template")) != 0)
						return true;
					
					right = me;
					return false;
				});
				
				if (right != null)
				{
					var action = right.children("Instances").attr("Action");
					var allRemove = action == undefined || action == "Remove";
					
					//选择Instance
					var instances = [];
					for (var i = 0; i < allInstance.length; i++)
					{
						var node = right.find("Instances > Instance[ID='" + allInstance[i].ID + "']");
						if (node.length == 0)
						{
							if (!allRemove)
								instances.push(allInstance[i]);
						}
						else
						{
							action = node.attr("Action");
							if (action == undefined || action == "Add")
							{
								instances.push(allInstance[i]);
								if (node.attr(_lang) != undefined)
									instances[instances.length - 1].Name = node.attr(_lang);
								if (node.attr("Mark") != undefined)
									instances[instances.length - 1].Mark = node.attr("Mark");
								instances[instances.length - 1].Node = node;
							}
						}
					}
					
					//下拉框里插入Instance
					var instance = $("[name=Instance]");
					for (var i = 0; i < instances.length; i++)
					{
						var sel = "";
						if (_id != "" && _widget.List != null && (_widget.List.Mark == instances[i].ID || _widget.List.Mark == instances[i].Mark))
							sel = " selected='selected'";

						instance.append("<option value='" + instances[i].ID + "' data-innerid='" + instances[i].InnerID + "' data-namespace='" + instances[i].Namespace + "'" + sel + ">" + instances[i].Name + "</option>");
						instance.children(":last").data("Node", instances[i].Node);
						instance.children(":last").data("Mark", instances[i].Mark);
					}
					
					//如果编辑，继续选择对象
					if (_id != "")
						instance.change();
				}
			}
		});
		return;
	}
	
	if (this.selectedIndex == 0)
	{
		$("[name=Object]")[0].length = 1;
		$("[name=Object]").change();
		return;
	}

	var instanceNode = $(this).children("option:selected").data("Node");

	$.ajax(
	{
		url : "ajax_objects.aspx?Namespace=" + $(this).children(":selected").data("namespace"),
		type : "GET",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
			var object = $("[name=Object]");
			object[0].length = 1;
			var allObjects = eval(data);

			var action = instanceNode.children("Objects").attr("Action");
			var allRemove = action == undefined || action == "Remove";

			var objects = [];
			for (var i = 0; i < allObjects.length; i++)
			{
				var node = instanceNode.find("Objects > Object[Name='" + allObjects[i].Name + "']");
				if (node.length == 0)
				{
					if (!allRemove)
						objects.push(allObjects[i]);
				}
				else
				{
					action = node.attr("Action");
					if (action == undefined || action == "Add")
					{
						objects.push(allObjects[i]);
						if (node.attr(_lang) != undefined )
							objects[objects.length - 1].Label = node.attr(_lang);
						else
							objects[objects.length - 1].Label = allObjects[i].Name;
						objects[objects.length - 1].Node = node;
					}
				}
			}
					
			//下拉框里插入Object
			for (var i = 0; i < objects.length; i++)
			{
				var sel = "";
				if (_id != "" && _widget.List != null && _widget.List.Object == objects[i].Name)
					sel = " selected='selected'";

				object.append("<option value='" + objects[i].ID + "'" + sel + ">" + objects[i].Label + "</option>");
				object.children(":last").data("Node", objects[i].Node);
				object.children(":last").data("Name", objects[i].Name);
			}
			object.change();
		}
	});
}

function Object_OnChange()
{
	$("[name=Condition]").val("").next()[0].length = 1;
	$("[name=Sort]").val("").next()[0].length = 1;
	$("#VarTable tbody :text").val("");
	
	if ($(this).val() == "")
	{
		$("#VarTable tbody select").each(function()
		{
			var me = $(this);
			me[0].length = 1;
		});

		return;
	}
	
	var objectNode = $(this).children("option:selected").data("Node");
	
	$.ajax(
	{
		url : "ajax_properties.aspx?ObjectID=" + $(this).val(),
		type : "GET",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
			//获取所有属性
			var allProperties = eval(data);
			
			//筛选可用属性
			var action = objectNode.children("Properties").attr("Action");
			var allRemove = action == undefined || action == "Remove";

			var properties = [];
			for (var i = 0; i < allProperties.length; i++)
			{
				var node = objectNode.find("Properties > Property[Name='" + allProperties[i].Name + "']");
				if (node.length == 0)
				{
					if (!allRemove)
						properties.push(allProperties[i]);
				}
				else
				{
					action = node.attr("Action");
					if (action == undefined || action == "Add")
					{
						properties.push(allProperties[i]);
						if (node.attr(_lang) != undefined )
							properties[properties.length - 1].Name = node.attr(_lang);
					}
				}
			}			
			
			//插入Property下拉菜单
			$("#VarTable tbody select").each(function()
			{
				var me = $(this);
				me.find("optgroup").remove();
				
				var html = "<optgroup label='" + _lang_global_function + "'>";
				for (var i = 0; i < _global_functions.length; i++)
				{
					html += "<option value='" + _global_functions[i] + "'>" + _global_functions[i] + "</option>";
				}
				html += "</optgroup>";

				html += "<optgroup label='" + _lang_global_var + "'>";
				for (var i = 0; i < _global_vars.length; i++)
				{
					html += "<option value='" + _global_vars[i] + "'>" + _global_vars[i] + "</option>";
				}
				html += "</optgroup>";

				html += "<optgroup label='" + _lang_property + "'>";
				for (var i = 0; i < properties.length; i++)
				{
					html += "<option value='" + properties[i].Value + "'>" + properties[i].Name + "</option>";
				}
				html += "</optgroup>";
				me.append(html);
			});
			
			//默认值
			$("#VarTable tbody tr").each(function()
			{
				var value = $(this).find("th").text();
				if (_id != "" && _widget.Record != null)
				{
					for (var i = 0; i < _widget.Record.Vars.length; i++)
					{
						if (_widget.Record.Vars[i].Name == value)
						{
							value = _widget.Record.Vars[i].Value;
							break;
						}
					}
				}

				$(this).find(":text").val(value);
			});
			
			//条件
			if (_id != "")
			{
				$("[name=Condition]").val(_widget.List.Condition);
			}
			else
			{
				var defaultCondition = objectNode.children("Conditions").attr("Default");
				if (defaultCondition != undefined)
					$("[name=Condition]").val(defaultCondition);
			}
				
			//条件快捷菜单
			var sel = $("#Condition select");
			objectNode.find("Conditions > Condition").each(function()
			{
				sel.append("<option value=\"" + $(this).attr("Value") + "\">" + $(this).attr(_lang) + "</option>");
			});
			
			//排序
			if (_id != "")
			{
				$("[name=Sort]").val(_widget.List.Sort);
			}
			else
			{
				var defaultSort = objectNode.children("Sorts").attr("Default");
				if (defaultSort != undefined)
					$("[name=Sort]").val(defaultSort);
			}
				
			//排序快捷菜单
			sel = $("#Sort select");
			objectNode.find("Sorts > Sort").each(function()
			{
				sel.append("<option value=\"" + $(this).attr("Value") + "\">" + $(this).attr(_lang) + "</option>");
			});
			
			//设置_id为空来表示加载完毕
			_id = "";
		}
	});
}

function Condition_OnChange()
{
	var val = $(this).prev().val();
	if (val.length > 0 && this.value.length > 0)
		$(this).prev().val(val + " and " + this.value);
	else
		$(this).prev().val(this.value);
}

function Sort_OnChange()
{
	$(this).prev().val(this.value);
}

function Property_OnChange()
{
	$(this).prev().val(this.value);
}

function Init()
{
	if (typeof(SetupIme) != "undefined")
		SetupIme();

	if (typeof(_page) == "undefined")
		return;
	
	if (_page == "index")
	{
		if (_id != "")
		{
			_widget = $.parseJSON(unescape($(window.parent.document.body).find("#" + _id).attr("json")));
			if (_widget.List != null)
				$("[name=PageSize]").val(_widget.List.PageSize);
			$("[name=Insert]").hide();
		}
		
		//初始化“当前模板”
		SetStatusMessage(_lang_get_skin);
		if (typeof(_widget) != "undefined" && _widget.Skin != _skin)
		{
			_skin = _widget.Skin;
			_skinName = _widget.SkinName;
		}
		var skin = $("[name=Skin] [value='" + _skin + "']");
		if (skin.length > 0)
			$("[name=Skin]").val(_skin);
		else
			$("[name=Skin]").append("<option value='" + _skin + "' selected='selected'>" + _skinName + "</option>");
		
		//debug状态下显示二级菜单
		if (_debug)
			$("h2:first").show();
		else
			$(".Preview").height($(".Preview").height() + $("h2").height());
		
		//加载配置
		LoadConfig();
		
		//绑定事件
		$("[name=Skin]").change(Skin_OnChange);
		$("[name=Widget]").change(Widget_OnChange);
		$("[name=PageSize]").change(PageSize_OnChange);
		$("h1 a").click(TabMenu_OnClick);
		$("h2 :radio").click(SubMenu_OnClick);
		$("[name=Instance]").change(Instance_OnChange);
		$("[name=Object]").change(Object_OnChange);
		$("#Condition").delegate("select", "change", Condition_OnChange);
		$("#Sort").delegate("select", "change", Sort_OnChange);
		$("#VarTable").delegate("select", "change", Property_OnChange);
		$("#VarTable tfoot :button").click(BuildList);
	}
}
Init();